package chapter01;

import java.util.HashMap;
import java.util.Stack;

public class IsValid {
    //栈
    public boolean isValid(String s) {
        HashMap<Character,Character> hashMap=new HashMap<>();
        Stack<Character> stack=new Stack<>();
        hashMap.put('(',')');
        hashMap.put('[',']');
        hashMap.put('{','}');
        if(s.length()%2==1||!hashMap.containsKey(s.charAt(0))){
            return false;
        }
        for(int i=0;i<s.length();i++){
            if(hashMap.containsKey(s.charAt(i))){
                stack.push(s.charAt(i));
            }else{
                if(stack.isEmpty()){ //防止栈空
                    return false;
                }else{
                    if(s.charAt(i)!=hashMap.get(stack.pop())){
                        return false;
                    }
                }
            }
        }
        return stack.size()==0; //栈中不剩下元素
    }
}
